﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
using System.Diagnostics;
using GLOBAL_DEF;

namespace PrintRipDemo
{
    public partial class Form1 : Form
    {


        public struct BOARDINFOMATION
        {
            public ushort nPrtStatus;//bit 0: Preload模式下，启动打印或者打印过程中，TaskBuffer为空，置1
            //bit 1: Preload模式下，启动打印或者打印过程中，data header出错，置1
            //bit 2: FIFO模式下，打印过程中数据流为空，置1
            //bit 3: 数据对空
            public byte nTrigStatus;      //光眼触发实时状态 1表高 0表示低
            public ushort nVailFifo;      //有效的fifo  proload 0 1 有效，最多存储256个任务
            public uint nUsedMemSize;   //写入的内存大小
            public uint nAllPrintCount; //所有任务的打印计数
            public Int64 nEncoderPos;    //编码器计数
            public uint nTaskID;
            public uint nSrcTrigCount;  //原始光眼的触发次数
            public uint nVailTrigCount; //有效的光眼计数
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
            public ushort[,] nPhTemp; //1个喷头4个温度  [4][4]
            public byte nPrinterStaus;
            public ushort nDDR3Memory; //判断数据是否达到打印机
            public uint nAPositon;//编码器A
            public uint nBPosition;//编码器B

            public uint nCupWaitTaskCounts;
            public uint nHeartBags;//心跳包计数
            public uint nExternalEmergencyStop;//外部紧急停止
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 126)]
            public uint[] nRev;//128 127

            public uint nMainBoardFpgaVer;  //fpga 版本号
            public uint nMainMcuVer;        //mcu  版本号
            public uint nMainCardId;    //板卡序列号
            public uint nIpAdr;          //ip地址
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
            public char[] szWaveFile;//波形文件名称
            public int bNetStatus;      //网络状态
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
            public float[] fVoltage;
            public float fPaperspeed; //皮带速度

            public int bSendStartCmd;
            public int nTagIndex;//发送的标签计数
            public int bDataIsFull;//数据是否缓存满

            public ushort nPrnStatus;//板卡状态[0~15] 低
            public ushort nPrnStatusExt;//板卡状态[0~15] 高
            public int nSendDataStaus;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 507)]
            public uint[] nAllRev; //512 511 510 509 507

        }



        public struct RIPINFO
        {
            public int nWidth;
            public int nHeight;
            public int ncolors;
            public int nGrayBit;
            public int nxdpi;
            public int nydpi;
        }


        public struct PRINT_PARAM
        {
            //色条-start
            public int nWidthType;//0表示图像宽度 1表示喷头宽度 从左往右
            public float fBarHeight;//色条高度
            public int nPosType;//色条位置
            public float fEdgeHeight;//离图像距离
            //色条-end

            //产品编号-start
            public float fxpos; //编号x位置相对于左上角
            public float fypos;//编号y位置相对于左上角
            public int nColorIndex;//编号颜色0=c 1=m 2=y 3=k
            public int nBarType;//固定为0
            public bool nClearBk;//是否清除背景
            public bool nProductID;//使能产品编号

            [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 256)]
            public string szSerialID;//产品编号字符串

            public int nFontSize;//字体大小
            //产品编号-end


            public int bEnableCalInkVol;//允许墨量计算
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
            public float[] fInkVol;//最多8种颜色 单位为ml(毫升) output

            //扫描打印-start
            public int bUseScanPrintMode;//扫描打印模式
            public int nImagePassCount;//分割的pass数, output
            public float fPaperStep;//走纸步进  参考值 单位mm, output
            public int nPassOverjets;//pass间重叠嘴
            public float fBPosition;//车头正向运动起始位置
            public float fCPosition;//车头反向运动起始位置 input+output
            public int bScanYMirror;//扫描Y镜像
            public int bImgSameDir;//单向打印使能
            public int bUseAdj;//打印校准图所有喷头发送一样的数据
            public int nScanPass;//扫描pass数
            //扫描打印-end

            public int nOnepassLRMirror;//左右安装反向
            public int bColorInImage;//色条在图像内

            //书刊双面打印-start
            public int bBookPrint;//使能双面打印
            public int nBookType;//0A4 1A3
            public int bFrontPage;//正面
            public int nColorFlagType;//色标类型
            public float fPaperWhiteEdge;//走纸白边
            public float fHeadWhiteEdge;//喷头白边
            public int bOnlyCalScanParam;//只测算扫面参数
            //书刊双面打印-end

            //书刊打印-start
            public float fxAreaPos;//x位置相对于左上角 mm
            public float fyAreaPos;//y位置相对于右上角 mm
            public float fAreaWidth;//宽度 mm
            public float fAreaHeight;//高度 mm
            public int bAreaPrint; //使能区域打印 
            public int nDYPrintDpi;//动态加载的dpi
            public int nDYPrintBit;//动态加载的位深度
            public float fScanPrintOffset;   //加减速区间
            public float fScanPrintLenOffset;//调节两个pass对齐
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
            byte[] nHPColorChannelIndex;//暂未使用
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
            public byte[] nOverJetsM;//一头一色喷头使用
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
            public byte[] nOverJetsY;////一头一色喷头使用
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
            public byte[] nOverJetsK;////一头一色喷头使用
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
            public int[] nColorOffset;//4个颜色的偏差值 一头一色喷头使用

    public int   nPassOverjetFeatherFileIndex;
	public float fScanStepOffset;
	public int   nScanDirMode;//
	public int   nfrontheaddelay;
	public int   nbackheaddelay;
	public int  bDoublePageKeepInk;
	public int  bCMYKBlock;//false cmyk按行存储  true表示cmyk块来存储
	public Int64 nVarModuleMask;//有可变数据的喷头
	public int    bVarPrintMode;//是可变数据打印模式
	public int    bFirstVarImage;//是第一张可变数据
	public int     nAllVarCount;//可变数据需要打印的数量

	public int     nImageYMirror;//垂直
	public int     nImageXMirror;//左右
	public int     nMultiThreadProcData;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
	public byte[]     bForbitPrint;
	public int     bScanNeedJumpWhite;
	public Int64  nScanPassInfoAdr;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
	public char[]     nOverAdj;//重叠嘴修正值 可以设置正负数
	public int     bNeedUseOverAdj;
	public int      nPlcPassCount;
	public int     bEnableScanDoublePage;//使能扫描双面打印
	public float    fScanDoubleOffset;//正数表示第一个面   负数表示第二个面
	public float    fBlackBarWidth;
	public float    fBlackBarHeight;
	public float    fHEdge;
	public float    fVEdge;
    public int      nBookDataMode;

    public Int64 pdc;
    public float fColorBarPos;///表示指定的色条的水平位置
    public float fColorBarWidth;///表示指定的色条的水平宽度
    public int nColorBarInkper;//色条墨量1-8
    public int nColorFlagInkper;//色标墨量1-8
    public int nxaarscanrepeatcout;//扫描需要重复的次数
    public float fScanPrintPosA;
    public float fScanPrintPosC;
    public bool bHeadDataClear;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 715)]
            public uint[] nRev;//保留参数 1023 1014 1008 1007 1004 1003 988 987 986
            public void init()
            {
                nRev = new uint[715];
                for (int i = 0; i < 715; i++)
                    nRev[i] = 0;
                fInkVol = new float[8];
                for (int i = 0; i < 8; i++)
                    fInkVol[i] = 0;
                nHPColorChannelIndex = new byte[128];
                for (int i = 0; i < 128; i++)
                    nHPColorChannelIndex[i] = 0;
                nOverJetsM = new byte[128];
                for (int i = 0; i < 128; i++)
                    nOverJetsM[i] = 0;
                nOverJetsY = new byte[128];
                for (int i = 0; i < 128; i++)
                    nOverJetsY[i] = 0;
                nOverJetsK = new byte[128];
                for (int i = 0; i < 128; i++)
                    nOverJetsK[i] = 0;
                nColorOffset = new int[4];
                for (int i = 0; i < 4; i++)
                    nColorOffset[i] = 0;

                bForbitPrint=new byte[256];
                for (int i = 0; i < 256; i++)
                    bForbitPrint[i] = 0;
            }
        }

        public struct PF_RIPHEADER
        {
            public uint nSignature;//0x5555
            public uint nXDPI;// Image XDPI //喷头方向
            public uint nYDPI;// Image YDPI 走纸方向
            public uint nBytesPerLine;// 
            public uint nHeight;//Image Height
            public uint nWidth;//Image Width
            public uint nPaperWidth;//NOUSE
            public uint nColors;//1=monochrome 4: KCMY, 6: KCMYLCLM, 8:KCMY+SPOT COLOR
            public uint nBits;//Bits per pixel
            public uint nReserve1;//Pass Number
            public uint nReserve2;
            public uint nReserve3;
        }



        double imgWidth = 0;
        double imgHeight = 0;
        uint nWhiteWidth = 0;
        bool m_bExitThread;
        RIPINFO m_ripinfo;

        /// <summary>  
        /// 由结构体转换为byte数组  
        /// </summary>  
        public static byte[] StructureToByte<T>(T structure)
         {
             int size = Marshal.SizeOf(typeof(T));
             byte[] buffer = new byte[size];
             IntPtr bufferIntPtr = Marshal.AllocHGlobal(size);
             try
             {
                 Marshal.StructureToPtr(structure, bufferIntPtr, true);
                 Marshal.Copy(bufferIntPtr, buffer, 0, size);
             }
             finally
             {
                 Marshal.FreeHGlobal(bufferIntPtr);
             }
             return buffer;
         }


       

        /// <summary>  
        /// 由byte数组转换为结构体  
        /// </summary>  
        public static T ByteToStructure<T>(byte[] dataBuffer)
        {
            object structure = null;
            int size = Marshal.SizeOf(typeof(T));
            IntPtr allocIntPtr = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.Copy(dataBuffer, 0, allocIntPtr, size);
                structure = Marshal.PtrToStructure(allocIntPtr, typeof(T));
            }
            finally
            {
                Marshal.FreeHGlobal(allocIntPtr);
            }
            return (T)structure;
        }
       

        [DllImport("GoodPrint.dll", EntryPoint = "PRT_InitPrinter", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int PRT_InitPrinter(IntPtr hNotifyWnd, uint nNotifyMsg);//连接设备 hNotifyWnd=0,nNotifyMsg=0;


        [DllImport("GoodPrint.dll", EntryPoint = "PRT_ClosePrinter", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern bool PRT_ClosePrinter();//软件退出时关闭打印机
    
        [DllImport("GoodPrint.dll", EntryPoint = "PRT_OpenCfgWnd", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern bool PRT_OpenCfgWnd(IntPtr hand, int nLevel);//喷印参数配置窗口 hand为窗口句柄 nLevel为3

        [DllImport("GoodPrint.dll", EntryPoint = "PRT_StartPrint", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int PRT_StartPrint(int nPrintDpi);//开始打印 nPrintDpi//打印精度图片dpi


        [DllImport("GoodPrint.dll", EntryPoint = "PRT_SendRipFile", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int PRT_SendRipFile(string szRipFilePath, int[] nOverJet, int nPrintCopys, bool bEnableOverJet, int nFeatherFileIndex, ref PRINT_PARAM colorbarinfo);
        // szRipFilePath为rip图像的绝对路径 nOverJet重叠嘴(喷头底部)  nPrintCopys打印份数
        ///bEnableOverJet 默认关闭重叠羽化处理 
        ///nFeatherFileIndex 指定羽化模板索引 羽化文件为软件目录/FeatherTemplate下的0=FeatherFile_00.dat 1=FeatherFile_01.dat
        // colorbarinfo 额外的参数信息

        [DllImport("GoodPrint.dll", EntryPoint = "PRT_StopPrint", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern bool PRT_StopPrint();//停止喷印

        [DllImport("GoodPrint.dll", EntryPoint = "PRT_GetPrintCounts", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int PRT_GetPrintCounts(int nNetModuleIndex);//获取打印计数  nNetModuleIndex板卡号，比如接了四块板卡nNetModuleIndex为0 1 2 3

         [DllImport("GoodPrint.dll", EntryPoint = "PRT_SetFlashPrint", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
         public static extern int PRT_SetFlashPrint(uint nNetModuleIndex, bool bOpen);//闪喷 //bOpen为1表示开启，0表示关闭

         [DllImport("GoodPrint.dll", EntryPoint = "PRT_GetPrintState", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
         public static extern int PRT_GetPrintState(int nNetModuleIndex);//查询打印状态：0:空闲；1:正在打印；大于等于2为等待打印
   

         [DllImport("GoodPrint.dll", EntryPoint = "PTR_GetNetBoardCount", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
         public static extern int PTR_GetNetBoardCount();//获取单个板卡的数量

         [DllImport("GoodPrint.dll", EntryPoint = "PRT_GetRipPreviewImage", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
         public static extern int PRT_GetRipPreviewImage(string szRipFilePath, ref RIPINFO pInfo, int nViewMode);//szRipFilePath rip文件路径 szPreviewFile目标预览图文件路径 nViewMode:0表示小图 1表示大图

         [DllImport("GoodPrint.dll", EntryPoint = "PRT_GetRollSpeed", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
         public static extern float PRT_GetRollSpeed(int NetModuleIndex);//获取皮带速度 单位mm/s

         [DllImport("GoodPrint.dll", EntryPoint = "PRT_EndAllSendData", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
         public static extern bool PRT_EndAllSendData();//通知所有打印控制模块数据已结束

         [DllImport("GoodPrint.dll", EntryPoint = "PRT_TriggerDelay", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
         public static extern bool PRT_TriggerDelay(float fTrigDelay);//设置走纸方向的延迟


         [DllImport("GoodPrint.dll", EntryPoint = "PRT_GetBoardCfgParam", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
         public static extern void PRT_GetBoardCfgParam(int nNetModuleIndex, ref BOARDCFGPARAM pCfg);//获取打印机的设置参数



         [DllImport("GoodPrint.dll", EntryPoint = "PRT_SetBoardCfgParam", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
         public static extern void PRT_SetBoardCfgParam(int nNetModuleIndex, ref BOARDCFGPARAM pCfg);//设置打印机的设置参数

        [DllImport("GoodPrint.dll", EntryPoint = "PRT_GetBoardInfo", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
       public static extern void  PRT_GetBoardInfo(int nNetModuleIndex,ref BOARDINFOMATION pInfo);

         [DllImport("GoodPrint.dll", EntryPoint = "PRT_SetLayoutMode", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
       public static extern void  PRT_SetLayoutMode(int nMode);


         [DllImport("GoodPrint.dll", EntryPoint = "PRT_SendRipMultiData", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
         public static extern  int  PRT_SendRipMultiData( byte[] psrc1,uint nsize1, byte[] psrc2,uint nsize2, byte[] psrc3,uint nsize3,
              byte[] psrc4, uint nsize4,  byte[] psrc5, uint nsize5, int[] nOverJet, int nPrintCopys, ref PF_RIPHEADER pHeader, bool bEnableOverJet, int nFeatherFileIndex, ref PRINT_PARAM colorbarinfo);

   

        public byte[] m_buffer;
        public string m_filename;
        public static uint MAX_MODULE_CNT = 8;//最大的板卡计数
        public Thread m_prtthread;//数据发送线程
        public Thread m_monitorthread;// 监控线程
        public int m_nTagIndex;
        public bool m_bstopprint;
        private int nStatus;
        SYS_PARAM sysparam;

        public string m_filename_c;
        public string m_filename_m;
        public string m_filename_y;
        public string m_filename_k;

        public string m_filename_cmyk;


    

        public Form1()
        {
            InitializeComponent();
        }
        private void monitormothed(Object obj)
        {
            string szparam;
            Form1 formx;
            int nModuleIndex = 0;//指定一个要查询的模组
            int nPrintCount;

            Control.CheckForIllegalCrossThreadCalls = false;

            formx = (Form1)obj;


            nModuleIndex = 0;
            while (m_bExitThread==false)
            {
                if (true)
                {
                    szparam = String.Format("{0:f}", PRT_GetRollSpeed(nModuleIndex) * 60 / 1000);
                    formx.spdbox.Text = szparam;

                    szparam = String.Format("{0:d}", m_nTagIndex);
                    formx.sendTagBox.Text = szparam;

                    nPrintCount = PRT_GetPrintCounts(nModuleIndex);
                    szparam = String.Format("{0:d}", nPrintCount);//暂时只取一个模组的信息
                    formx.prttagbox.Text = szparam;

                    nStatus = PRT_GetPrintState(nModuleIndex);
                    switch (nStatus)
                    {
                        case 0:
                            szparam = "空闲"; break;
                        case 1:
                            szparam = "正在打印"; break;
                        default:
                            szparam = "等待触发"; break;
                    }
                    formx.sysmsgbox.Text = szparam;
                }
                Thread.Sleep(600);
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            int nerror;
            string szPath = System.Environment.CurrentDirectory;
            byte[] path = System.Text.Encoding.Default.GetBytes(szPath);
            int nBoardCount;
            BOARDCFGPARAM pCfg=new BOARDCFGPARAM();

            tabControl1.TabPages[0].Text = "prn-图像";
            tabControl1.TabPages[1].Text="bmp-图像";
            //
            nerror = PRT_InitPrinter((IntPtr)0, 0);
            if (nerror != 0)
            {
                MessageBox.Show(String.Format("初始化打印设备失败，错误代码:{0}", nerror));
                startbutton.Enabled = false;
            }
            PRT_SetLayoutMode(1);//从上往下

            //获取配置参数
            GetSysParam();
            nBoardCount = PTR_GetNetBoardCount();
            for (int i = 0; i < nBoardCount; i++)
            {
                PRT_GetBoardCfgParam(i, ref pCfg);
                pCfg.bYImgMirror = sysparam.nHeadYMirror;
                pCfg.bXImgMirror = sysparam.nHeadXMirror;
                pCfg.bPhInstallCov = sysparam.nHeadDir;


                pCfg.fPrinterToTrigger = sysparam.fHeadStdPos[i];
                pCfg.nPrintMode = (uint)sysparam.nPrintMode;
                pCfg.nTrigMode = (uint)sysparam.nTriggerMode;
                pCfg.nWaveSel = (uint)sysparam.nWaveMode;
                pCfg.fTriggerProtectLen = sysparam.fTriggerProtectLen;
                PRT_SetBoardCfgParam(i, ref pCfg);
            }
            m_bExitThread = false;
            m_monitorthread = new Thread(monitormothed)
            {

                IsBackground = true

            };
            m_monitorthread.Start(this);

            comboBox1.SelectedIndex=0;
            tabControl1.SelectedIndex = Properties.Settings.Default.image_type;

        }

        //选择要打印的prn  从上往下打印
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;//该值确定是否可以选择多个文件
            dialog.Title = "请选择rip图像";
            dialog.Filter = "Rip File(*.prn)|*.prn";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string file = dialog.FileName;
                RIPINFO ripinfo=new RIPINFO();
                int nResult;
                string previewfile;
                int npos;
                int nViewMode = 1;//0表示清晰 1表示缩略



                nResult = PRT_GetRipPreviewImage(file, ref ripinfo, nViewMode);

                m_ripinfo = ripinfo;
                previewfile = file;
                npos= previewfile.LastIndexOf(".");
                previewfile=previewfile.Remove(npos, 1);
                previewfile=previewfile.Insert(npos, "_");
                previewfile += ".ripvw";

                textBox1.Text = file;

                pictureBox1.Load(previewfile);

           

                textBox_prn.Text = String.Format("宽度:{0:f2}mm,  高度:{1:f2}mm,  位深度:{2},颜色数:{3}\r\n\r\n喷头方向精度:{4} 走纸方向精度:{5}", ripinfo.nWidth/(float)ripinfo.nxdpi*25.4, ripinfo.nHeight/(float)ripinfo.nydpi*25.4, ripinfo.nGrayBit,
                    ripinfo.ncolors, ripinfo.nxdpi, ripinfo.nydpi);
                textBox4.Text = String.Format("{0}", ripinfo.nydpi);
         
                m_filename = file;

            }
        }

       

       
        //打印机属性窗口
        private void button2_Click(object sender, EventArgs e)
        {
            PRT_OpenCfgWnd((IntPtr)null , 3);
        }


        //读取配置参数
        public void GetSysParam()
        {
            string file = System.Windows.Forms.Application.StartupPath + "\\sysparam.cfg";
            Stream stream;


            if (!File.Exists(file))
            {
                sysparam = new SYS_PARAM();
                sysparam.init();
            }
            else
            {

                int nSize = Marshal.SizeOf(typeof(SYS_PARAM));
                byte[] buf = new byte[nSize];

                stream = File.OpenRead(file);
                if (stream.Length > 0)
                {
                    stream.Position = 0;
                    stream.Read(buf, 0, nSize);
                    stream.Close();
                    sysparam = PUBLIC_WAY.GByteToStructure<SYS_PARAM>(buf);
                }
                else
                {
                    sysparam = new SYS_PARAM();
                    sysparam.init();
                }

            }
        }

        private void prtmethod(Object obj)
        {
            Form1 formx = (Form1)obj; 
            int nTagCount;
            int nResult=0;
            bool  bFindError=false;
            string szparam;
            int nPrintCopys=1;//打印份数 每个rip任务 重复打印的次数
            int[] nOverJets=new int[128]; //喷头间重叠嘴
            int nFeatherIndex ;
            PRINT_PARAM colorbarinfo = new PRINT_PARAM();
            int nBoardCount=PTR_GetNetBoardCount();
            bool bEnableOverjet = true;//喷头间重叠使能
            string filename;

            if (formx.m_filename_cmyk == "")
                filename = formx.m_filename;
            else
                filename = formx.m_filename_cmyk;

            colorbarinfo.init();

            
            Control.CheckForIllegalCrossThreadCalls = false;

            nFeatherIndex = (int)formx.sysparam.nFeatherIndex;

            for (int i = 0; i < 128; i++)
                nOverJets[i] = (int)formx.sysparam.nOverJets[i];//赋值为0
            
            szparam = formx.textBox3.Text;
            nTagCount = System.Convert.ToInt32(szparam);
            m_nTagIndex = 0;
            colorbarinfo.fBarHeight = formx.sysparam.fColorBarHeight;
            colorbarinfo.fEdgeHeight = formx.sysparam.fColorBarEdge;
            colorbarinfo.nWidthType = formx.sysparam.nColorBarWidth;
            colorbarinfo.nPosType = formx.sysparam.nColorBarPos;


            colorbarinfo.fxpos = formx.sysparam.fxpos;
            colorbarinfo.fypos = formx.sysparam.fypos;
            colorbarinfo.nColorIndex = formx.sysparam.nColorIndex;
            colorbarinfo.nClearBk = formx.sysparam.nClearBk;
            colorbarinfo.nBarType = formx.sysparam.nBarType;
            colorbarinfo.nProductID = formx.sysparam.nProductID;

            colorbarinfo.szSerialID = "产品号:yundayin 20211223";//指定产品编号
            if (formx.checkBox1.Checked)
                colorbarinfo.bUseAdj=1;
            else

                colorbarinfo.bUseAdj=0;

            colorbarinfo.init();

            colorbarinfo.bHeadDataClear = true;


            for (int i = 0; i < nTagCount; i++)//模拟多个任务的发送
            {
                if (formx.m_bstopprint)
                    break;

              
                if ((nResult = PRT_SendRipFile(filename, nOverJets, nPrintCopys, bEnableOverjet, nFeatherIndex, ref colorbarinfo)) < 0)
                {
                    bFindError = true;
                    break;
                }
                
            


                if(bFindError)
                    break;

                if (nResult > 0)
                    formx.m_nTagIndex = nResult;
            }


            if (bFindError == true)
                PRT_StopPrint();//发现错误自动停止打印
            else
                PRT_EndAllSendData();//结束数据发送

            if (bFindError == true)
            {
                string szerro=String.Format("错误代码:{0:d}",nResult);


                MessageBox.Show(szerro, "数据发送");
            }

        }

        public static byte[] GStructureToByte<T>(T structure)
        {
            int size = Marshal.SizeOf(typeof(T));
            byte[] buffer = new byte[size];
            IntPtr bufferIntPtr = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.StructureToPtr(structure, bufferIntPtr, true);
                Marshal.Copy(bufferIntPtr, buffer, 0, size);
            }
            finally
            {
                Marshal.FreeHGlobal(bufferIntPtr);
            }
            return buffer;
        }


        //开始打印
        private void button3_Click(object sender, EventArgs e)
        {
            int bResult;
            int nPrtDpi = 0;

            m_filename_cmyk = "";
            if (tabControl1.SelectedIndex == 0)
            {
                if (m_filename == "" || m_filename == null)
                {
                    MessageBox.Show("没有选择RIP图片文件或者是不支持的文件格式");

                    return;
                }
            }
            else
            {
                if (m_filename_c == null && m_filename_m == null && m_filename_y == null && m_filename_k == null)
                {
                    MessageBox.Show("没有选择BMP图片文件或者是不支持的文件格式");

                    return;
                }

                if (m_filename_c == "" && m_filename_m == "" && m_filename_y == "" && m_filename_k == "")
                {
                    MessageBox.Show("没有选择BMP图片文件或者是不支持的文件格式");

                    return;
                }
                //生成新的图像
                PF_RIPHEADER rihead = new PF_RIPHEADER();
                int nlinebytes_c=0;
                int nlinebytes_m=0;
                int nlinebytes_y=0;
                int nlinebytes_k=0;

                int nwidth_c;
                int nwidth_m;
                int nwidth_y;
                int nwidth_k;


                int nheight_c=0;
                int nheight_m=0;
                int nheight_y=0;
                int nheight_k=0;

                int nMaxLineBytes = 0;
                int nMaxHeight = 0;
                Image imgPhoto_c, imgPhoto_m, imgPhoto_y, imgPhoto_k;

                if (m_filename_c != null)
                {
                    imgPhoto_c = Image.FromFile(m_filename_c);
                    nwidth_c = imgPhoto_c.Width;

                    nheight_c = imgPhoto_c.Height;
                    if (nheight_c > nMaxHeight)
                        nMaxHeight = nheight_c;
                }

                if (m_filename_m != null)
                {
                    imgPhoto_m = Image.FromFile(m_filename_m);
                    nwidth_m = imgPhoto_m.Width;


                    nheight_m = imgPhoto_m.Height;
                    if (nheight_m > nMaxHeight)
                        nMaxHeight = nheight_m;
                }

                if (m_filename_y != null)
                {
                    imgPhoto_y = Image.FromFile(m_filename_y);
                    nwidth_y = imgPhoto_y.Width;

                    nheight_y = imgPhoto_y.Height;
                    if (nheight_y > nMaxHeight)
                        nMaxHeight = nheight_y;
                }

                if (m_filename_k != null)
                {
                    imgPhoto_k = Image.FromFile(m_filename_k);
                    nwidth_k = imgPhoto_k.Width;

                    nheight_k = imgPhoto_k.Height;
                    if (nheight_k > nMaxHeight)
                        nMaxHeight = nheight_k;
                }





                Stream stream_c, stream_m, stream_y, stream_k;
                byte[] buffer_c=null;
                byte[] buffer_m = null;
                byte[] buffer_y=null;
                byte[] buffer_k=null;

                byte[] ncolor_c = new byte[8];
                byte[] ncolor_m = new byte[8];
                byte[] ncolor_y = new byte[8];
                byte[] ncolor_k = new byte[8];





                if (m_filename_c != null)
                {
                    stream_c = File.OpenRead(m_filename_c);
                    buffer_c = new byte[stream_c.Length - 62];

                    
                    stream_c.Position = 54;
                    stream_c.Read(ncolor_c, 0, 8);

                    stream_c.Position = 62;
                    stream_c.Read(buffer_c, 0, (int)stream_c.Length - 62);
                    if (ncolor_c[0] == 0)
                    {
                        for (int k = 0; k < ((int)stream_c.Length - 62); k++)
                        {
                            buffer_c[k] = (byte)~buffer_c[k];
                        }
                    }

                    nlinebytes_c = ((int)stream_c.Length - 62) / nheight_c;
                    if (nlinebytes_c > nMaxLineBytes)
                        nMaxLineBytes = nlinebytes_c;
                }

                if (m_filename_m != null)
                {
                    stream_m = File.OpenRead(m_filename_m);
                    buffer_m = new byte[stream_m.Length - 62];

                    stream_m.Position = 54;
                    stream_m.Read(ncolor_m, 0, 8);

                    stream_m.Position = 62;
                    stream_m.Read(buffer_m, 0, (int)stream_m.Length - 62);

                    if (ncolor_m[0] == 0)
                    {
                        for (int k = 0; k < ((int)stream_m.Length - 62); k++)
                        {
                            buffer_m[k] = (byte)~buffer_m[k];
                        }
                    }

                    nlinebytes_m = ((int)stream_m.Length - 62) / nheight_m;
                    if (nlinebytes_m > nMaxLineBytes)
                        nMaxLineBytes = nlinebytes_m;
                }

                if (m_filename_y != null)
                {
                    stream_y = File.OpenRead(m_filename_y);
                    buffer_y = new byte[stream_y.Length - 62];

                    stream_y.Position = 54;
                    stream_y.Read(ncolor_y, 0, 8);

                    stream_y.Position = 62;
                    stream_y.Read(buffer_y, 0, (int)stream_y.Length - 62);

                    if (ncolor_y[0] == 0)
                    {
                        for (int k = 0; k < ((int)stream_y.Length - 62); k++)
                        {
                            buffer_y[k] = (byte)~buffer_y[k];
                        }
                    }

                    nlinebytes_y = ((int)stream_y.Length - 62) / nheight_y;
                    if (nlinebytes_y > nMaxLineBytes)
                        nMaxLineBytes = nlinebytes_y;
                }

                if (m_filename_k != null)
                {
                    stream_k = File.OpenRead(m_filename_k);
                    buffer_k = new byte[stream_k.Length - 62];

                    stream_k.Position = 54;
                    stream_k.Read(ncolor_k, 0, 8);

                    stream_k.Position = 62;
                    stream_k.Read(buffer_k, 0, (int)stream_k.Length - 62);

                    if (ncolor_k[0] == 0)
                    {
                        for (int k = 0; k < ((int)stream_k.Length - 62); k++)
                        {
                            buffer_k[k] = (byte)~buffer_k[k];
                        }
                    }

                    nlinebytes_k = ((int)stream_k.Length - 62) / nheight_k;
                    if (nlinebytes_k > nMaxLineBytes)
                        nMaxLineBytes = nlinebytes_k;
                }

              
     

               

                byte[] buffer = new byte[nMaxLineBytes * nMaxHeight * 4];

                Array.Clear(buffer, 0, nMaxLineBytes * nMaxHeight * 4);

                if (buffer_c != null)
                {
                    for (int i = 0; i < nheight_c; i++)
                    {
                        Array.Copy(buffer_c, (nheight_c-1-i) * nlinebytes_c, buffer, (i * 4 + 1) * nMaxLineBytes, nlinebytes_c);
                    }
                }

                if (buffer_m != null)
                {
                    for (int i = 0; i < nheight_m; i++)
                    {
                        Array.Copy(buffer_m, (nheight_m-1-i) * nlinebytes_m, buffer, (i * 4 + 2) * nMaxLineBytes, nlinebytes_m);
                    }
                }

                if (buffer_y != null)
                {

                    for (int i = 0; i < nheight_y; i++)
                    {
                        Array.Copy(buffer_y, (nheight_y-1-i) * nlinebytes_y, buffer, (i * 4 + 3) * nMaxLineBytes, nlinebytes_y);
                    }
                }


                if (buffer_k != null)
                {
                    for (int i = 0; i < nheight_k; i++)
                    {
                        Array.Copy(buffer_k, (nheight_k-1-i) * nlinebytes_k, buffer, (i * 4 + 0) * nMaxLineBytes, nlinebytes_k);
                    }
                }
                rihead.nSignature = 0x5555;
                rihead.nBits = (uint)comboBox1.SelectedIndex + 1;
                rihead.nBytesPerLine = (uint)nMaxLineBytes;
                rihead.nColors = 4;
                rihead.nHeight = (uint)nMaxHeight;
                rihead.nWidth = (uint)(rihead.nBytesPerLine * 8 / rihead.nBits);
                rihead.nXDPI = (uint)System.Convert.ToInt32(textBox2_cmyk.Text);
                rihead.nYDPI = 600;

                m_filename_cmyk = Path.GetDirectoryName(Application.ExecutablePath) + "\\use.prn";
                Stream streamprn = new FileStream(m_filename_cmyk, FileMode.Create);

                BinaryWriter sw = new BinaryWriter(streamprn);
                sw.Write(GStructureToByte<PF_RIPHEADER>(rihead));
                sw.Write(buffer);
                sw.Close();
            }

            //获取配置参数
            GetSysParam();


            BOARDCFGPARAM pCfg = new BOARDCFGPARAM();
            int nBoardCount = PTR_GetNetBoardCount();
            for (int i = 0; i < nBoardCount; i++)//设置图像灰度位数，采用read modify write方式修改
            {
                PRT_GetBoardCfgParam(i, ref pCfg);
                if (m_ripinfo.nGrayBit == 2)
                {
                    pCfg.nGrayBit = 0;
                }
                else
                {
                    if (pCfg.nGrayBit == 0)
                        pCfg.nGrayBit = 3;
                }


                PRT_SetBoardCfgParam(i, ref pCfg);
            }

 
            string szparam = textBox4.Text;
            nPrtDpi = System.Convert.ToInt32(szparam);
           
            nStatus = 0;
            //设置车头总体偏移
            PRT_TriggerDelay(sysparam.fPhToTrigger);
            bResult = PRT_StartPrint(nPrtDpi);
            if (bResult !=0)
            {
                string szerror = String.Format("错误代码:{0}", bResult);
                MessageBox.Show(szerror, "启动打印失败");
                return;
            }

             m_prtthread = new Thread(prtmethod)
            {

                IsBackground = true

            };

             m_bstopprint = false;
             m_nTagIndex = 0;
             m_prtthread.Start(this);

             stopbutton.Enabled = true;
             startbutton.Enabled = false;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            

            m_bstopprint = true;
            Thread.Sleep(500);

            PRT_StopPrint();

            this.m_prtthread.Abort();

            stopbutton.Enabled = false;
            startbutton.Enabled = true;
        }

        private void groupBox4_Enter(object sender, EventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {

        }


        private void button31_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            form2.InitDataView();
           

            form2.ShowDialog();
        }

        private void form_close(object sender, FormClosedEventArgs e)
        {
            m_bExitThread = true;
            Thread.Sleep(1000);//等待线程结束
            PRT_ClosePrinter();
        }

        private void selectindex(object sender, EventArgs e)
        {
            int nIndex = tabControl1.SelectedIndex;

            if (nIndex == 0)
            {
                textBox5.Hide();
                button3.Hide();

                textBox6.Hide();
                button4.Hide();

                textBox7.Hide();
                button5.Hide();

                textBox8.Hide();
                 button6.Hide();

                button1.Show();
                textBox1.Show();

                pictureBox1.Show();
                pictureBox_c.Hide();
                pictureBox_m.Hide();
                pictureBox_y.Hide();
                pictureBox_k.Hide();

                textBox_prn.Show();
                textBox_c.Hide();
                textBox_m.Hide();
                textBox_y.Hide();
                textBox_k.Hide();

                label7.Hide();
                comboBox1.Hide();

                textBox2_cmyk.Hide();


            }
            else
            {
                textBox5.Show();
                button3.Show();

                textBox6.Show();
                button4.Show();

                textBox7.Show();
                button5.Show();

                textBox8.Show();
                button6.Show();

                textBox_c.Show();

                pictureBox1.Hide();
                pictureBox_c.Show();
                pictureBox_m.Show();
                pictureBox_y.Show();
                pictureBox_k.Show();

                button1.Hide();
                textBox1.Hide();
              
                textBox_prn.Hide();
                textBox_c.Show();
                textBox_m.Show();
                textBox_y.Show();
                textBox_k.Show();

                label7.Show();
                comboBox1.Show();

                textBox2_cmyk.Show();
            }




            Properties.Settings.Default["image_type"] = nIndex;
            Properties.Settings.Default.Save();
        }

        private void button6_Click(object sender, EventArgs e)//C
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;//该值确定是否可以选择多个文件
            dialog.Title = "请选择位图文件";
            dialog.Filter = "BMP File(*.bmp)|*.bmp";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                 string file = dialog.FileName;
                 Image imgPhoto = Image.FromFile(file);


                if (imgPhoto.PixelFormat != PixelFormat.Format1bppIndexed)
                 {
                     MessageBox.Show("只支持单色位图");
                     return;
                 }
                    

                 textBox8.Text = file;

                 pictureBox_c.Load(file);
                 pictureBox_c.Show();
                 pictureBox_m.Hide();
                 pictureBox_y.Hide();
                 pictureBox_k.Hide();

                 textBox_c.Show();
                 textBox_m.Hide();
                 textBox_y.Hide();
                 textBox_k.Hide();


                 m_filename_c = file;

                 textBox_c.Text = String.Format("宽度:{0:d}像素,  高度:{1:d}像素,  位深度:{2:d}", imgPhoto.Width, imgPhoto.Height, 1);
                 //bmp.Size.Width;
            }
        }

        private void button7_Click(object sender, EventArgs e)//M
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;//该值确定是否可以选择多个文件
            dialog.Title = "请选择位图文件";
            dialog.Filter = "BMP File(*.bmp)|*.bmp";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string file = dialog.FileName;

                Image imgPhoto = Image.FromFile(file);


                if (imgPhoto.PixelFormat != PixelFormat.Format1bppIndexed)
                {
                    MessageBox.Show("只支持单色位图");
                    return;
                }

                textBox5.Text = file;

                pictureBox_m.Load(file);
                pictureBox_c.Hide();
                pictureBox_m.Show();
                pictureBox_y.Hide();
                pictureBox_k.Hide();

                textBox_c.Hide();
                textBox_m.Show();
                textBox_y.Hide();
                textBox_k.Hide();

                m_filename_m = file;


                textBox_m.Text = String.Format("宽度:{0:d}像素,  高度:{1:d}像素,  位深度:{2:d}", imgPhoto.Width, imgPhoto.Height, 1);
            }
        }

        private void button8_Click(object sender, EventArgs e)//Y
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;//该值确定是否可以选择多个文件
            dialog.Title = "请选择位图文件";
            dialog.Filter = "BMP File(*.bmp)|*.bmp";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string file = dialog.FileName;
                Image imgPhoto = Image.FromFile(file);


                if (imgPhoto.PixelFormat != PixelFormat.Format1bppIndexed)
                {
                    MessageBox.Show("只支持单色位图");
                    return;
                }

                textBox6.Text = file;

                pictureBox_y.Load(file);
                pictureBox_c.Hide();
                pictureBox_m.Hide();
                pictureBox_y.Show();
                pictureBox_k.Hide();

                textBox_c.Hide();
                textBox_m.Hide();
                textBox_y.Show();
                textBox_k.Hide();

                m_filename_y = file;


                textBox_y.Text = String.Format("宽度:{0:d}像素,  高度:{1:d}像素,  位深度:{2:d}", imgPhoto.Width, imgPhoto.Height, 1);
            }
        }

        private void button9_Click(object sender, EventArgs e)//K
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;//该值确定是否可以选择多个文件
            dialog.Title = "请选择位图文件";
            dialog.Filter = "BMP File(*.bmp)|*.bmp";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string file = dialog.FileName;

                Image imgPhoto = Image.FromFile(file);


                if (imgPhoto.PixelFormat != PixelFormat.Format1bppIndexed)
                {
                    MessageBox.Show("只支持单色位图");
                    return;
                }

                textBox7.Text = file;

                pictureBox_k.Load(file);
                pictureBox_c.Hide();
                pictureBox_m.Hide();
                pictureBox_y.Hide();
                pictureBox_k.Show();

                textBox_c.Hide();
                textBox_m.Hide();
                textBox_y.Hide();
                textBox_k.Show();

                m_filename_k = file;


                textBox_k.Text = String.Format("宽度:{0:d}像素,  高度:{1:d}像素,  位深度:{2:d}", imgPhoto.Width, imgPhoto.Height, 1);
            }
        }

       

        private void c_click(object sender, EventArgs e)
        {
            pictureBox_c.Show();
            pictureBox_m.Hide();
            pictureBox_y.Hide();
            pictureBox_k.Hide();

            textBox_c.Show();
            textBox_m.Hide();
            textBox_y.Hide();
            textBox_k.Hide();
        }

        private void m_click(object sender, EventArgs e)
        {
            pictureBox_c.Hide();
            pictureBox_m.Show();
            pictureBox_y.Hide();
            pictureBox_k.Hide();

            textBox_c.Hide();
            textBox_m.Show();
            textBox_y.Hide();
            textBox_k.Hide();
        }

        private void y_click(object sender, EventArgs e)
        {
            pictureBox_c.Hide();
            pictureBox_m.Hide();
            pictureBox_y.Show();
            pictureBox_k.Hide();

            textBox_c.Hide();
            textBox_m.Hide();
            textBox_y.Show();
            textBox_k.Hide();
        }

        private void k_click(object sender, EventArgs e)
        {
            pictureBox_c.Hide();
            pictureBox_m.Hide();
            pictureBox_y.Hide();
            pictureBox_k.Show();

            textBox_c.Hide();
            textBox_m.Hide();
            textBox_y.Hide();
            textBox_k.Show();
        }
    }

}


